package view;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

import javax.swing.JTextField;

import controller.IExchangerController;

public class ClipBoardAccess implements ClipboardOwner {
	private JTextField textField;
	private IExchangerController control;
	
	public ClipBoardAccess(JTextField textField) {
		super();
		this.textField = textField;
	}
	
	public void setControl(IExchangerController control){
		this.control = control;
	}
	
	@Override
	public void lostOwnership(Clipboard cb, Transferable t) {
		
	}
	
	public void setClipboardContents(String s) {
		StringSelection ss = new StringSelection(s);
		Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
		cb.setContents(ss, this);
	}
	
	public void setClipboardContentsWithTextFieldContents(){
		setClipboardContents(textField.getText());
	}

	public String getClipboardContents() {
		Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard()
				.getContents(null);

		try {
			if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
				String text = (String) t
						.getTransferData(DataFlavor.stringFlavor);
				return text;
			}
		} catch (UnsupportedFlavorException e) {
			System.out.println(e);
		} catch (IOException e) {
			System.out.println(e);
		}
		return null;
	}
	
	public void setTextFieldContentsWithClipboardContents(){
		this.textField.setText(getClipboardContents());
		this.control.refreshView();
		
	}
}
